<template>
  <div class="system-tenant-dialog-container">
    <el-dialog
      :title="state.dialog.title"
      v-model="state.dialog.isShowDialog"
      :close-on-click-modal="false"
      draggable
      width="520px"
    >
      <el-form
        ref="tenantDialogFormRef"
        :model="state.ruleForm"
        :rules="formRules"
        size="default"
        label-width="100px"
      >
        <el-row :gutter="35">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="租户名称" prop="name">
              <el-input
                v-model="state.ruleForm.name"
                placeholder="请输入租户名称"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            v-if="!state.dialog.editId"
            :xs="24"
            :sm="24"
            :md="24"
            :lg="24"
            :xl="24"
            class="mb20"
          >
            <el-form-item label="管理员邮箱" prop="adminEmailAddress">
              <el-input
                v-model="state.ruleForm.adminEmailAddress"
                placeholder="请输入管理员邮箱"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col
            v-if="!state.dialog.editId"
            :xs="24"
            :sm="24"
            :md="24"
            :lg="24"
            :xl="24"
            class="mb20"
          >
            <el-form-item label="管理员密码" prop="adminPassword">
              <el-input
                v-model="state.ruleForm.adminPassword"
                type="password"
                placeholder="请输入管理员密码"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onCancel" size="default">取 消</el-button>
          <el-button
            type="primary"
            @click="submitValidate(tenantDialogFormRef)"
            size="default"
            >{{ state.dialog.submitTxt }}</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="systemTenantDialog">
import { nextTick, reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import _ from "lodash";
import { useTenantApi } from "/@/api/tenant/index";
import { verifyPasswordPowerful, verifyEmail } from "/@/utils/toolsValidate";

// 定义子组件向父组件传值/事件
const emit = defineEmits(["refresh"]);

// 引入租户 Api 请求接口
const tenantApi = useTenantApi();

// 定义变量内容
const tenantDialogFormRef = ref();
const state = reactive({
  ruleForm: {
    name: "", // 租户名称
    adminEmailAddress: "", // 管理员邮箱地址
    adminPassword: "", // 管理员密码
    concurrencyStamp: "",
  },
  dialog: {
    isShowDialog: false,
    type: "",
    editId: "",
    title: "",
    submitTxt: "",
  },
});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{ required: true, message: "请输入租户名称！", trigger: "blur" }],
  adminEmailAddress: [
    { required: !state.dialog.editId, message: "请输入管理员邮箱！", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (
          !state.dialog.editId &&
          state.ruleForm.adminEmailAddress &&
          !verifyEmail(value)
        ) {
          callback(new Error("邮箱格式不正确！"));
          return;
        }
        callback();
      },
      trigger: "blur",
    },
  ],
  adminPassword: [
    { required: !state.dialog.editId, message: "请输入管理员密码！", trigger: "blur" },
    {
      validator: (rule: any, value: any, callback: any) => {
        if (
          !state.dialog.editId &&
          state.ruleForm.adminPassword &&
          !verifyPasswordPowerful(value)
        ) {
          callback(
            new Error("密码不符合要求，必须包含：字母、数字、特殊字符，长度在6-16之间！")
          );
          return;
        }
        callback();
      },
      trigger: "blur",
    },
  ],
});

// 提交验证
const submitValidate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      onSubmit();
    } else {
      console.warn("未验证通过!", fields);
    }
  });
};

// 打开弹窗
const openDialog = (type: string, row: RowTenantType) => {
  nextTick(() => {
    state.dialog.editId = "";
    tenantDialogFormRef.value?.resetFields();
    if (type === "edit") {
      state.ruleForm = _.cloneDeep(row) as any;
      state.dialog.editId = row.id;
      state.dialog.title = "修改租户";
      state.dialog.submitTxt = "修 改";
    } else {
      state.dialog.title = "新增租户";
      state.dialog.submitTxt = "新 增";
    }
    state.dialog.type = type;
    state.dialog.isShowDialog = true;
  });
};

// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
  closeDialog();
};

// 提交
const onSubmit = () => {
  if (state.dialog.type == "edit") {
    // 修改
    let editForm = {
      name: state.ruleForm.name,
      concurrencyStamp: state.ruleForm.concurrencyStamp,
    };
    tenantApi
      .updateTenant(state.dialog.editId, editForm)
      .then((result) => {
        if (result) {
          ElMessage.success("修改成功！");
          closeDialog(); // 关闭弹窗
          emit("refresh");
        }
      })
      .catch((err) => {
        console.error("提交出错：", err);
      });
    return;
  }

  // 添加
  tenantApi
    .addTenant(state.ruleForm)
    .then(async (result) => {
      await grantMenuPermissions(result.id);
      if (result) {
        ElMessage.success("添加成功！");
        closeDialog(); // 关闭弹窗
        emit("refresh");
      }
    })
    .catch((err) => {
      console.error("提交出错：", err);
    });
};

// 赋予菜单权限
const grantMenuPermissions = async (tenantId: string) => {
  return new Promise((resolve, reject) => {
    tenantApi
      .setMenuPermissions(tenantId)
      .then((result: any) => {
        resolve(result);
      })
      .catch((err: any) => {
        reject(err);
        console.error("赋予菜单权限出错：", err);
      });
  });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
